package nio.socket.nonblocking;


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Calendar;


public class NonBlockingServer {
    public static void main(String[] args) {
        start(9999);
    }

    public static void start(int port) {
        try {
            ServerSocketChannel server = ServerSocketChannel.open();
            server.bind(new InetSocketAddress(port));
            server.configureBlocking(false);//设置为false的话没有客户端请求连接的话accept不会阻塞，会直接返回null
            System.out.println("启动服务器....");
            while (!Thread.currentThread().isInterrupted()) {
                SocketChannel client = server.accept();
                //如果没有请求客户端请求连接的话client会为null
                if (client == null) {
                    Thread.currentThread().sleep(1000);
                }else {
                    client.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
                    while (client.read(buffer) != -1) {
                        if (buffer.position() > 0) {//大于0表示有读取到数据，否则休眠100毫秒后再读取
                            buffer.clear();
                            buffer.put(Calendar.getInstance().getTime().toLocaleString().getBytes());
                            buffer.flip();
                            client.write(buffer);
                            buffer.clear();
                        }else{
                            Thread.sleep(100);
                        }
                    }
                    System.out.println("end");
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  new Thread(()->{

        }).start();
    }
}
